<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    let list = [
      { id: 1, name: '节点1', pid: '' },
      { id: 11, name: '节点1-1', pid: 1 },
      { id: 111, name: '节点1-1-1', pid: 11 },
      { id: 12, name: '节点1-2', pid: 1 },
      { id: 2, name: '节点2', pid: '' },
      { id: 21, name: '节点2-1', pid: 2 }
    ]
    /*
    目标结果
    let list = [
      {id: 1, name: '节点1', pid: '' ,children: [
        {id: 11, name: '节点1-1', pid: 1, children: [
           {id: 111, name: '节点1-1-1', pid: 11}
        ]},
        {id: 12, name: '节点1-2', pid: 1},
      ]},
      {id: 2, name: '节点2', pid: '', children: [
        {id: 21, name: '节点2-1', pid: 2}
      ]},
    ]
    */
    //  🍎方法1
    // list.forEach(el => {
    //   let children = list.filter(item => item.pid === el.pid)
    //   if (children.length > 0) {
    //     el.children = children
    //   }
    // })

    // let result = list.filter(el => el.pid === '')
    // console.log(result)

    // 🍎方法2
    // function translateListoTree(pid) {
    //   let result = list.filter(el => el.pid === pid)
    //   result.forEach(el => {
    //     let children = translateListoTree(el.id)
    //     if (children.length > 0) {
    //       el.children = children
    //     }
    //   })
    //   return result
    // }
    // console.log(translateListoTree(''))

    function translateListoTree(arr, pid) {
      let result = arr.filter(el => el.pid === pid)
      result.forEach(el => {
        let children = translateListoTree(arr, el.id)
        if (children.length > 0) {
          el.children = children
        }
      })
      return result
    }
    console.log(translateListoTree(list, ''))
  </script>
</html>
